using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Text.RegularExpressions;
using SqlWebAdmin;

[WebService(Namespace = "http://codeplex.com/sqlserver/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class AutoComplete : WebService
{

    public AutoComplete()
    {
    }

    private List<string> SortCompletionList(List<string> tempList, string textMatch)
    {
        int sizeList = tempList.Count;
        int sizeText = textMatch.Length;
        int pos = 0;
        string tempElement;

        /*
        // NEW ALGORITHM 07.05.07
        string tempTrunc;
        
        for (int i = 0; i < sizeList; i++)
        {
            tempTrunc = tempList[i].Substring(0, sizeText).ToUpper();
            if (tempTrunc.Equals(textMatch))
            {
                tempElement = tempList[i];
                tempList.RemoveAt(i);
                tempList.Insert(pos++, tempElement);
                i--;
            }
        }*/
        
        
        // OLD ALGORITHM
        for (int i = 0; i < sizeList; i++)
        {
            for (int j = 0; j < sizeText; j++)
            {
                if (tempList[i][j].ToString().ToUpper() != textMatch[j].ToString().ToUpper())
                {
                    break;
                }
                if (j == sizeText - 1)
                {
                    if (i > 0)
                    {
                        tempElement = tempList[i];
                        tempList.RemoveAt(i);
                        tempList.Insert(pos++, tempElement);
                        i--;
                    }
                }
            }
        } 

        return tempList;
    }

    [WebMethod(EnableSession=true)]
    public string[] GetCompletionList(string prefixText, int count)
    {
        // prefixText is the text that the user has typed so far for this term.
        // count is the number of choices that have been set to show. (probably want to ignore this for intellisense)
        // To show no autocomplete options (when there are no more options), retrun new string[0];
        prefixText = prefixText.ToUpper();

        List<string> staticKeywords = (List<string>)Session["staticKeywords"];
        List<string> tableNames = (List<string>)Session["tableNames"];
        List<string> columnNames = (List<string>)Session["columnNames"];

        List<string> items = new List<string>(0);
        
        items.AddRange(staticKeywords);
        items.AddRange(tableNames);
        items.AddRange(columnNames);

        items = SortCompletionList(items, prefixText);

        return items.ToArray();
    }
}